package com.truyen.persistence.dao.impl;

import java.util.List;

import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.truyen.persistence.dao.BookmarkChapterDao;
import com.truyen.persistence.dao.base.GenericJpaBaseDaoImpl;
import com.truyen.persistence.entity.Account;
import com.truyen.persistence.entity.BookmarkChapter;
import com.truyen.utils.PagingInfo;

@Repository
public class BookmarkChapterDaoImpl extends GenericJpaBaseDaoImpl<BookmarkChapter, Long>
		implements BookmarkChapterDao {

	public BookmarkChapterDaoImpl() {
		super(BookmarkChapter.class);
	}

	@Override
	public List<BookmarkChapter> getLstByAccountWithPaging(Account account,
			PagingInfo pInfo) {
		CriteriaBuilder critBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<BookmarkChapter> query = critBuilder
				.createQuery(BookmarkChapter.class);
		Root<BookmarkChapter> entity = query.from(BookmarkChapter.class);
		Predicate p = critBuilder.conjunction();
		p = critBuilder.and(p,
				critBuilder.equal(entity.<Account> get("account"), account));
		query = query.where(p);
		query.orderBy(critBuilder.desc(entity.get("id")));
		TypedQuery<BookmarkChapter> q = entityManager.createQuery(query);
		long count = countByQuery(query, entity);
		pInfo.setCount(count);
		pInfo.setTotalPage((int)Math.ceil((double)count/pInfo.getSizePerPage()));		
		q.setFirstResult(pInfo.getStartResult());
		q.setMaxResults(pInfo.getSizePerPage());
		List<BookmarkChapter> lst = q.getResultList();
		return (lst.size() > 0) ? lst : null;
	}

	@Override
	public BookmarkChapter findByAccountIdTruyenIdChapter(Account account,
			Long idTruyen, Long idChapter) {
		CriteriaBuilder critBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<BookmarkChapter> query = critBuilder
				.createQuery(BookmarkChapter.class);
		Root<BookmarkChapter> entity = query.from(BookmarkChapter.class);
		Predicate p = critBuilder.conjunction();
		p = critBuilder.and(p,
				critBuilder.equal(entity.<Account> get("account"), account),
				critBuilder.equal(entity.<Long> get("idTruyen"), idTruyen),
				critBuilder.equal(entity.<Long> get("idChapter"), idChapter));
		query = query.where(p);
		TypedQuery<BookmarkChapter> q = entityManager.createQuery(query);
		q.setFirstResult(0);
		q.setMaxResults(1);
		List<BookmarkChapter> lst = q.getResultList();
		return (lst.size() > 0) ? lst.get(0) : null;
	}

}
